var recorderManager = null;
import startRecord from 'dingtalk-jsapi/api/device/audio/startRecord';
import stopRecord from 'dingtalk-jsapi/api/device/audio/stopRecord';
import play from 'dingtalk-jsapi/api/device/audio/play';
import stop from 'dingtalk-jsapi/api/device/audio/stop';
import download from 'dingtalk-jsapi/api/device/audio/download';
import util from "/common/js/util.js";
import Qs from "qs";
/**
  {mediaId: "@lR_PD298BnsLiw0AALAg_JzMB9Hd2AZlUWoJ-uAA", remoteUrl: "https://static.dingtalk.com/media/lR_PD298BnsLiw0AALAg_JzMB9Hd2AZlUWoJ-uAA.ogg", duration: 2.46}
 */
const pageSize = 5;
var Timeout = null;
var Timeout2 = null;
var time_obj = {};
var item_timeout = null;
var app = getApp();
const base_residueTime = 240; //297 280  240
const base_residueTimeLength = "4:59";
var mediaData = {};
Page({
  data: {
    scrollTop: 0,
    toView: "",
    btnStatus: "stop",
    payIng: false, //红灯闪烁
    recorderManager: null,
    recordAudioArr: [
      // {mediaId: "@lR_PD298BnsLiw0AALAg_JzMB9Hd2AZlUWoJ-uAA", remoteUrl: "https://static.dingtalk.com/media/lR_PD298BnsLiw0AALAg_JzMB9Hd2AZlUWoJ-uAA.ogg", duration: 2.46,"note":"这是我的学习笔记"
      // ,"createTime":"2024-07-10 09:44:25"},
      // {mediaId: "@lR_PD298BnsLiw0AALAg_JzMB9Hd2AZlUWoJ-uAA", remoteUrl: "https://static.dingtalk.com/media/lR_PD298BnsLiw0AALAg_JzMB9Hd2AZlUWoJ-uAA.ogg", duration: 2.46,"note":""
      // ,"createTime":"2024-07-10 09:44:25"}
    ], // 音频文件数组
    unSubmitArr: [
      // {"mediaId":"@lR_PD298BnsLiw0AALAg_JzMB9Hd2AZlUWoJ-uAA","remoteUrl":"https://static.dingtalk.com/media/lR_PD298BnsLiw0AALAg_JzMB9Hd2AZlUWoJ-uAA.ogg","duration":299,"note":"","bookId":"1811641576373571585","bookName":"恒丽哲学手册","index":"0","userId":"2363192520970306","userName":"刘庆峰","value":"哲学原点","startPage":"13","endPage":"14","chapter":"哲学原点"},{"mediaId":"@lR_PD298BnsLiw0AALAg_JzMB9Hd2AZlUWoJ-uAA","remoteUrl":"https://static.dingtalk.com/media/lR_PD298BnsLiw0AALAg_JzMB9Hd2AZlUWoJ-uAA.ogg","duration":2.46,"note":"","bookId":"1811641576373571585","bookName":"恒丽哲学手册","index":"0","userId":"2363192520970306","userName":"刘庆峰","value":"哲学原点","startPage":"13","endPage":"14","chapter":"哲学原点"}
    ], //未提交数组
    mediaData: null,
    startTime: 0,
    timeLength: "00:00", //显示录制时长
    residueTime: util.copy(base_residueTime), //倒计时 秒
    residueTimeLength: base_residueTimeLength, //剩余录制时间
    queryData: {},

    dataList: [],
    page: 1,
    pageSize: pageSize,

    img_page: 1,
    img_pageSize: pageSize,

    img_totalResult: pageSize,
    showLoadMore: false,
    showLoadMoreTxt: "over",
    totalResult: pageSize,
    view: false, //查看模式
    loginUserId: "", //当前登录人员id
    enableNative: false,
    //缺卡日期列表
    tagData: [],
    advanceData: [], //提前读书日期

    advanceDateList: [], //可选择的 提前打卡日期列表
    calendarRangeList: [], //用于提示可选日期范围
    calendarValue: "", //选中日历后的  补卡日期
    advanceValue: "", //提前读书日期
    sub_loadding: false,
    showVisible: false, //打开打卡成功提示的弹层
    showModalData: {},

    residueTitle: "", //剩余时间的提示弹层
    residueContent: "",
    residueVisible: false,

    basicVisible: false, //读书规则弹层

    nextMsgVisible:false,//下一阶段模版弹层
    nextMsgContent: "",//下一阶段目标内容

    imgArr: [], //图片数组
    showImg:false,//显示图片

    rightBtns: [
      {
          text: '删除',
          bgColor: '#FF2B00',
          color: '#fff',
      },
      
  ],
  showDeleteImg:false,//开启删除

  showImgUser:false,//特定人员显示 图片上传
  },
  onLoad(e) {
    // console.log("-进入");
    // console.log(e);
    let loginUserId = app.prototype.$userId;

    let userName=app.prototype.$userName;
    this.setData({
      queryData: e,
      loginUserId
    });
    let view = false;
    if (loginUserId == e.userId) {
      view = false;
    } else {
      view = true;
    }
    if(!view&&(userName=='刘庆峰'||userName=='曾旻銮'||userName=='庄嫚艺'||userName=='黄丽红'||userName=='张放'||userName=='张和荣'||userName=='杨柳')){
      this.setData({
        showImgUser:true
      })
    }
    this.resetFn();
    this.setData({
      view,
      // unSubmitArr: [],
      recordAudioArr: [],
      btnStatus: "stop"
    });

    this.getUnSubmitArr();
    try {
      if (Timeout) {
        clearTimeout(Timeout);
      }
    } catch (error) {

    }

    // console.log("--app.prototype.$userId:",loginUserId);

    //  this.setData({
    //   enableNative:true
    // })
    dd.getSystemInfo({
      success: (res) => {
        // res.platform;
        console.log("--res.platform", res.platform);
        if (res.platform == "iOS") {
          this.setData({
            enableNative: true
          })
        }
      }
    })

    if (app.prototype.$userName == "刘庆峰") {
      this.setData({
        enableNative: true
      })
    }

    dd.setNavigationBar({
      title: `${e.userName}的读书笔记`,
      success: () => {},
      fail: () => {},
      complete: () => {},
    });
    this.initFn();

    const updateManager = dd.getUpdateManager()

    updateManager.onCheckForUpdate(function (res) {
      if (res.hasUpdate) {
        updateManager.onUpdateReady(function (ret) {
          //console.log(ret.version) // 更新版本号
          dd.confirm({
            title: '更新提示',
            content: '新版本已经准备好，是否重启应用？',
            success: function (res) {
              if (res.confirm) {
                // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                updateManager.applyUpdate()
              }
            }
          })
        })
      }
    })
    // this.showIntegralIcon();

    // this.testShowFn();

  },
  onShow() {
    // 页面显示

    // console.log(util.copy(base_residueTime));

    //如果遇到提交时突然来电时需要解除loadding
    if(this.data.sub_loadding){
      this.setData({
        sub_loadding: false
      })
    }
    
  },
  onHide(){
    console.log("----小程序隐藏了;;");
  },
  getUnSubmitArr() {
    this.setData({
      unSubmitArr: app.prototype.unSubmitArr
    })
  },
  setUnSubmitArr(unSubmitArr) {
    app.prototype.unSubmitArr = unSubmitArr;
    this.getUnSubmitArr();
  },
  calendar_modal(ref) {
    this.calendar_modal = ref;
  },
  advancer_modal(ref) {
    this.advancer_modal = ref;
  },
  getIsLogin() {
    let api = "/user/info/getIsLogin",
      list = {};
    app.$post(api, list).then(re => {
      try {
        if (re.code == 401) {
          app.authLoginFn().then(res => {
            // console.log("--detail--res:",res);
            this.tableList();
            this.getLackCardsFn();

          })
        } else {
          this.tableList();
          this.getLackCardsFn();

        };
      } catch (error) {}
    }).catch(err => {

    });
  },
  clickOpenCalendar() {
    this.calendar_modal.handleOpen();
  },
  clickOpenAdvance() {
    this.advancer_modal.handleOpen();
  },
  clearCalendarValue() {
    this.setData({
      calendarValue: ""
    })
  },
  clearAdvanceValue() {
    this.setData({
      advanceValue: ""
    })
  },
  //日历选中日期
  onCalendarSub(e) {
    this.setData({
      calendarValue: e
    })
  },
  //日历选中日期
  onAdvanceSub(e) {
    this.setData({
      advanceValue: e
    })
  },

  playFn(e) {
    let arr = e.currentTarget.dataset.arr;
    let index = e.currentTarget.dataset.index;
    let id = e.currentTarget.dataset.id;
    let list = this.data[arr];
    let item = list[index];
    // console.log("--item:",item);
    let that = this;

    download({
      mediaId: id,
      success: (suc) => {
        console.log("--suc", suc);
        if (!item.play) {
          play({
            localAudioId: suc.localAudioId,
            success: (ms) => {
              // item.play=true;
              // item.startTime=0;
              let startTime = item.startTime;
              // item.duration2=item.duration;
              let duration = item.duration2;
              list.forEach(row => {
                if (row.mediaId == id) {
                  row.play = true;
                  row.startTime = 0;
                  row.duration2 = row.duration;
                  // let duration=row.duration2;
                } else {
                  row.play = false;
                  row.timeLength = that.format(row.duration);
                }
              })



              // item.timeLength="00:00";
              // console.log("list",list);
              that.setData({
                [`${arr}`]: list
              });


            },
            fail: (e) => {
              console.log("--错误", e);
            },
            complete: () => {},
          });
        } else {
          stop({
            localAudioId: suc.localAudioId,
            success: (ms) => {
              item.play = false;
              item.timeLength = that.format(item.duration);
              that.setData({
                [`${arr}`]: list
              })
              // let ti=time_obj[id];
              // console.log("--ti:",ti);
              // clearInterval(ti)
            },
            fail: (e) => {
              // console.log("--错误",e);
            },
            complete: () => {},
          })
        }


      },
      fail: () => {},
      complete: () => {},
    });

  },
  inputChange1(e) {
    this.setData({
      "queryData.startPage": e
    })
  },
  inputChange2(e) {
    // console.log(e);
    this.setData({
      "queryData.endPage": e
    })
  },
  format(seconds) { //秒转化为分钟格式
    let s = Math.trunc(seconds);
    let minInt = Math.floor(s / 60);
    let min = minInt >= 10 ? minInt : '0' + minInt;
    s -= 60 * min;
    let sec = s >= 10 ? s : '0' + s;
    return min + ':' + sec;
  },
  resetFn() {
    //重置参数
    this.setData({
      timeLength: "0:00",
      startTime: 0,
      payIng: false,
      residueTimeLength: util.copy(base_residueTimeLength),
      residueTime: util.copy(base_residueTime)
    })

  },

  initFn() {

    this.getIsLogin();
    //  this.showIntegralIcon2()
  },
  zero_audio(ref) {
    this.zero_audio = ref
  },
  tableList(obj) {
    let api = "/user/book/noteList";
    let list = {
      page: this.data.page,
      pageSize: this.data.pageSize,
      bookId: this.data.queryData.bookId,
      userId: this.data.queryData.userId,
      chapter: this.data.queryData.value
    };
    if (obj) {
      list = util.mergeObj(list, obj)
    }
    //    console.log("--list:",list);
    let that = this;
    this.setData({
      showLoadMoreTxt: "load"
    });

    // console.log(this.data.totalnum,this.data.totalResult);
    //debugger
    if (this.data.dataList.length >= this.data.totalResult && this.data.totalResult != 0) {
      this.setData({
        showLoadMoreTxt: "over"
      })
      dd.stopPullDownRefresh();
      return false;
    }
    dd.showLoading({
      content: '数据加载中...',
    })
    let dataList = this.data.recordAudioArr;
    app.$post(api, list).then(res => {
      dd.stopPullDownRefresh()
      dd.hideLoading();
      if (res.code == 200) {

        let arr_list = dataList.concat(res.data.list);
        arr_list.forEach(r => {

          r.timeLength = this.format(r.duration)
        })
        let page = this.data.page;
        page = page + 1;
        // console.log(JSON.stringify(arr_list[0]));
        this.setData({
          totalResult: res.data.totalResult,
          page,
          recordAudioArr: arr_list,
          showLoadMoreTxt: "over"
        });
        this.zero_audio.initF();
      } else {
        util.message(res.message);

      }
    })
  },

  //获取缺卡日期
  getLackCardsFn() {
    let api = "/user/book/getLackCards";
    let dataObj = {};
    app.$post(api, dataObj).then(res => {

      if (res.code == 200) {
        let arr = [];
        res.data.forEach(r => {
          let json = {
            date: r
          };
          arr.push(json);
        })
        this.setData({
          tagData: arr
        })
        this.calendar_modal.initFn();

      }
    });
    let userName = app.prototype.$userName;
    // if(userName=="刘庆峰"||userName=="庄嫚艺"||userName=="曾旻銮"){
    // }
    this.getAdvancerCardsFn();

  },
  getAdvancerCardsFn() {
    let api = "/user/book/getAdvanceCards";
    let dataObj = {};
    app.$post(api, dataObj).then(res => {

      if (res.code == 200) {
        let arr = [];
        
        if (res.data.now) {
          let json = {
            date: res.data.now
          };
          arr.push(json)
        }


        this.setData({
          advanceData: arr,
          calendarRangeList: res.data.times
        })
        this.advancer_modal.initFn();

      }
    })
  },
  addNoteFn(arr) {
    dd.showLoading({
      content: '数据提交中...',
    })
    this.setData({
      sub_loadding: true
    })
    // let api = "/user/book/addNote";
    // let list = {
    //   ...this.data.queryData
    // };
    // list.chapter=this.data.queryData.value
    // if(obj){
    //   list=util.mergeObj(list,obj)
    // }
    let api = "/user/book/addNoteBatch";
    let ms_type = 0; //消息类型 0正常打卡 1 补卡 2提前读书
    let calendarValue = this.data.calendarValue;
    let advanceValue = this.data.advanceValue;
    let list = [];
    let dataObj = {};
    arr.forEach(element => {
      element = util.mergeObj(element, this.data.queryData)
      element.chapter = this.data.queryData.value
      list.push(element);
    });
    // console.log("--list:",list);
    // return ;
    let that = this;
    dataObj.list = JSON.stringify(list);
    if (calendarValue && util.isNotEmpty(this.data.tagData)) {
      api = "/user/book/patchNoteBatch";
      dataObj.date = calendarValue;
      ms_type = 1;
    }
    if (advanceValue && util.isNotEmpty(this.data.advanceData)) {
      api = "/user/book/advanceNoteBatch";
      dataObj.date = advanceValue;
      ms_type = 2;
    }
    app.$post(api, dataObj).then(res => {
      dd.stopPullDownRefresh()
      dd.hideLoading();
      if (res.code == 200) {
        this.setData({
          "queryData.note": "",
          "queryData.pageNum": "",
          "queryData.startPage": "",
          "queryData.endPage": "",
          btnStatus: "stop",
          sub_loadding: false,
          // unSubmitArr: []
        })
        this.setUnSubmitArr([]);
        this.searchFn();
        this.showIntegralIcon(res.data, ms_type);
        this.showIntegralIcon2(res.data, ms_type);

        this.addReadLogFn();
        this.getLackCardsFn();
      } else {
        this.setData({
          sub_loadding: false
        })
        util.message(res.message);

      }
    })
  },
  addReadLogFn() {
    let api = "/user/book/addReadLog";
    let list = {
      ...this.data.queryData
    };

    let that = this;


    app.$post(api, list).then(res => {

      if (res.code == 200) {


      } else {
        util.message(res.message);

      }
    })
  },
  requestDeleteFn(item) {
    // deleteNote
    let api = "/user/book/deleteNote";
    let list = {
      ...item
    };

    let that = this;


    app.$post(api, list).then(res => {

      if (res.code == 200) {
        this.searchFn()

      } else {
        //  util.message(res.message);

      }
    })
  },
  submitErrorFn(msg) {
    // deleteNote
    let api = "/user/book/submitError";
    let list = {
      msg
    };
    let that = this;
    app.$post(api, list).then(res => {
      if (res.code == 200) {} else {
        //  util.message(res.message);
      }
    })
  },
  onPullDownRefresh() {
    // 页面被下拉
    this.setData({
      showLoadMoreTxt: "load"
    });
    this.searchFn();
    this.getLackCardsFn();
  },
  searchFn(obj) {
    this.setData({
      page: 1,
      pageSize,
      recordAudioArr: []
    });
    this.tableList(obj)
  },
  onScrollToLower() {
    // console.log("---触底了!");
    this.tableList()
  },

  //开始录音
  startRecordFn() {
    this.setData({
      btnStatus: "start"
    })
    this.resetFn();
    // recorderManager.start({ duration: 60 });
    let that = this;



    startRecord({
      maxDuration: 300,
      success: (res) => {
        console.log("--开始录制res", res);
        //  res.play=false;
        // that.setData({
        //   mediaData:res
        // })
        mediaData = res;
        console.log(res);
        console.log("--mediaData", mediaData);
        Timeout = setInterval(() => {
          let payIng = that.data.payIng;
          let startTime = that.data.startTime;
          //  let nowTime=new Date();
          startTime = startTime + 1;
          //  console.log("----startTime",startTime);
          let timeLength = that.format(startTime);
          //  console.log("----timeLength",timeLength);
          let residueTime = that.data.residueTime;
          residueTime = residueTime - 1;
          let residueTimeLength = that.format(residueTime);
          that.setData({
            startTime,
            timeLength,
            residueTime,
            residueTimeLength
          });
          if (residueTime == 0) {
            console.log("--自动停止录音");
            that.autoStopRecordFn();
          } else {
            // if(app.prototype.$userName=="刘庆峰"){
            //   that.testGet();
            // }
          }

        }, 1000);
        Timeout2 = setInterval(() => {
          let payIng = that.data.payIng;
          // let startTime=that.data.startTime;
          that.setData({
            payIng: !payIng,

          });
        }, 1000);
      },
      fail: () => {},
      complete: () => {},
    });
  },

  //点击 停止录音
  stopRecordFn() {
    this.setData({
      btnStatus: "stop"
    })
    // recorderManager.stop();

    clearTimeout(Timeout);
    this.setData({
      payIng: false
    })
    let that = this;
    stopRecord({
      success: (res) => {
        console.log("--停止录制res", res);
        let duration = Math.round(res.duration); //4舍五入 等于300 则为5分钟
        res.roundDuration = duration;
        //  this.addNoteFn(res);
        res.timeLength = that.format(res.duration);

        //  console.log("--时长:",timeLength);
        let unSubmitArr = that.data.unSubmitArr;
        unSubmitArr.unshift(res);
        // that.setData({
        //   unSubmitArr
        // });
        that.setUnSubmitArr(unSubmitArr)
      },
      fail: () => {},
      complete: () => {},
    });

  },
  testGet() {
    dd.alert({
      title: '消息提示',
      content: JSON.stringify(mediaId),
      buttonText: '我知道了',
      success: () => {},
      fail: () => {},
      complete: () => {},
    });
  },
  //自动再录音一次
  autoStopRecordFn() {
    let that = this;
    clearTimeout(Timeout);
    clearTimeout(Timeout2);
    let mediaId = mediaData.mediaId
    stopRecord({
      success: (res) => {
        //console.log("--停止录制res",res);
        let duration = Math.round(res.duration); //4舍五入 等于300 则为5分钟
        res.timeLength = that.format(res.duration);
        res.roundDuration = duration;

        let unSubmitArr = that.data.unSubmitArr;
        unSubmitArr.unshift(res);
        // that.setData({
        //   unSubmitArr
        // })
        that.setUnSubmitArr(unSubmitArr)

        that.startRecordFn();
      },
      fail: (err) => {
        // if (app.prototype.$userName == "刘庆峰") {
        // }
        err.msg = "mediaId:" + mediaId;
        let msg = JSON.stringify(err)
        dd.alert({
          title: '录音异常提示',
          content: msg,
          buttonText: '我知道了',
          success: () => {},
          fail: () => {},
          complete: () => {},
        });
        that.submitErrorFn(msg);

      },
      complete: () => {},
    });

  },
  submitFn() {

    let startPage = this.data.queryData.startPage;
    let endPage = this.data.queryData.endPage;
    let unSubmitArr = this.data.unSubmitArr;

    if (this.data.btnStatus == "stop") {
      if (util.isEmpty(unSubmitArr)) {
        util.message("未进行录音,先进行录音 后填写页码 再提交！")
        return false;
      }
    }
    if (util.isEmpty(startPage)) {
      util.message("请输入起始页码！")
      return false;
    }
    if (isNaN(startPage)) {
      util.message("起始页码请输入数字!")
      return false;
    }

    if (util.isEmpty(endPage)) {
      util.message("请输入结束页码！")
      return false;
    }
    if (isNaN(endPage)) {
      util.message("结束页码请输入数字!")
      return false;
    }
    this.setData({
      "queryData.startPage": startPage.trim(),
      "queryData.endPage": endPage.trim()
    })
    if (this.data.btnStatus == "stop") {

      this.addNoteFn(unSubmitArr);

    } else {
      this.setData({
        btnStatus: "stop",
        sub_loadding: true,
        payIng: false
      })

      clearTimeout(Timeout);
      clearTimeout(Timeout2);


      stopRecord({
        success: (res) => {
          let duration = Math.round(res.duration); //4舍五入 等于300 则为5分钟
          res.roundDuration = duration;
          let unSubmitArr = this.data.unSubmitArr;
          // unSubmitArr=[res];
          unSubmitArr.unshift(res);
          this.setUnSubmitArr(unSubmitArr);
          this.addNoteFn(unSubmitArr);
        },
        fail: () => {},
        complete: () => {},
      });
    }
    //pageNum




  },
  bindKeyInput(e) {
    let key = "queryData.note";
    // util.debounce(() => {

    // }, 300);
    this.setData({
      [`${key}`]: e,
    });
  },
  onDeleteFn(index) {
    dd.confirm({
      title: '温馨提示',
      content: '是否删除该录音文件?',
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      success: (result) => {
        if (result.confirm) {
          this.delete(index);
        }
      },
    });
  },
  deleteFn(e) {
    let index = e.currentTarget.dataset.index;

    dd.confirm({
      title: '温馨提示',
      content: '是否删除该录音文件?',
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      success: (result) => {
        if (result.confirm) {
          this.delete(index);
        }
      },
    });
  },
  deleteUnSubmitFn(e) {
    let index = e.currentTarget.dataset.index;

    dd.confirm({
      title: '温馨提示',
      content: '是否删除该录音文件?',
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      success: (result) => {
        if (result.confirm) {
          let unSubmitArr = this.data.unSubmitArr;
          unSubmitArr.splice(index, 1);
          // this.setData({
          //   unSubmitArr
          // })
          this.setUnSubmitArr(unSubmitArr)
        }
      },
    });
  },
  delete(index) {
    let recordAudioArr = this.data.recordAudioArr;
    // recordAudioArr.splice(index, 1);
    // this.setData({
    //   recordAudioArr
    // })
    let item = recordAudioArr[index];
    this.requestDeleteFn(item);

  },
  //打卡成功提示
  showIntegralIcon(data, ms_type) {
    let content = "";
    if (data.fullMap && data.fullMap.type == 1) {
      content += `${data.fullMap.note}获得${data.fullMap.integral}积分\n`;
    }
    if (data.daysMap && data.daysMap.type == 1) {
      content += `连续打卡获得${data.daysMap.integral}积分\n`;
    }
    if (data.readMap && data.readMap.type == 1) {
      content += `读书获得${data.readMap.integral}积分\n`;
    }
    let ms_txt = "";
    switch (ms_type) {
      case 0:
        ms_txt = "打卡";
        break;
      case 1:
        ms_txt = "补卡";
        break;
      case 2:
        ms_txt = "提前读书";
        break;
      default:
        break;
    }
    if (content) {
      let title = `${ms_txt}成功,恭喜获得以下奖励:`;

      dd.showModal({
        cells: [{
            image: 'http://220.161.77.66:10111/app_file/images/sys/dakachengong2.png',
            title,
            content,
          }

        ],
        image: 'image示例值',
        title: 'title示例值',
        content: 'content示例值',
        buttonLabels: ['知道了'],
        success: (res) => {
          const {
            buttonIndex
          } = res;
          this.showIntegralIcon2(data, ms_type)

        },
        fail: () => {},
        complete: () => {},
      });
    }

  },
  testShowFn() {
    let data = {};
    data = {
      readMap: {
        type: 0,
        residueTimes: "2.5",
        integral: 2,
        rankingNum: 3


      }
    };
    let ms_type = true;
    //    this.showIntegralIcon(data, ms_type);

    this.showIntegralIcon2(data, ms_type);

  },
  showIntegralIcon2(data, ms_type) {
    data.ms_type = ms_type;
    // let cardName = ms_type ? "补卡" : "打卡";
    let ms_txt = "";
    switch (ms_type) {
      case 0:
        ms_txt = "打卡";
        break;
      case 1:
        ms_txt = "补卡";
        break;
      case 2:
        ms_txt = "提前读书";
        break;
      default:
        break;
    }
    this.setData({
      showModalData: data
    });
    if (data.readMap) {
      if (data.readMap.type == 0 && data.readMap.residueTimes) {

        this.setData({
          residueTitle: `${ms_txt}未成功!`,
          residueContent: `还剩余${data.readMap.residueTimes}分钟即可${ms_txt}成功`
        })
        this.residueVisibleOpen()
      }
      //下一阶段 分数数差距显示
      if(data.readMap.nextMsg){
        
        this.setData({
          nextMsgContent: data.readMap.nextMsg
        })
        this.nextMsgVisibleOpen()
      }
      if (data.readMap.type == 1 && data.readMap.rankingNum) {
        this.setData({
          showVisible: true
        })
      }
    }

  },
  residueVisibleOpen() {
    this.setData({
      residueVisible: true
    })
  },
  residueVisibleClose() {
    this.setData({
      residueVisible: false
    })
  },

  nextMsgVisibleOpen() {
    this.setData({
      nextMsgVisible: true
    })
  },
  nextMsgVisibleClose() {
    this.setData({
      nextMsgVisible: false
    })
  },
  handleClose() {
    this.setData({
      showVisible: false
    })
  },
  onShareAppMessage() {

    let p = Qs.stringify(this.data.queryData);
    let path = '/pages/note/noteDetail/noteDetail';
    let url = `${path}?${p}`;
    return {
      title: '恒丽书城',
      desc: `${this.data.queryData.userName}的读书笔记`,
      path: url,
    };
  },

  handleTapLink() {
    this.setData({
      basicVisible: true
    });
  },
  handleTitleAlert() {
    dd.alert({
      title: '消息提示',
      content: "为确保录音质量，请确保屏幕在不息屏下录音，避免由于息屏导致录音播放无声音的情况!",
      buttonText: '我知道了',
      success: () => {},
      fail: () => {},
      complete: () => {},
    });
  },
  handleClose() {
    this.setData({
      basicVisible: false
    });
  },
  previewImageFn(e) {
    let img = e.currentTarget.dataset.img;
    let index = e.currentTarget.dataset.index;
    
    if (!img) {
      return;
    }
    let urls=[];
    let imgArr= this.data.imgArr;
    imgArr.forEach(r=>{
      urls.push(r.imgUrl);
    })
    dd.previewImage({
      urls,
      current: index,
      success: () => {},
      fail: () => {},
      complete: () => {},
    });
  },


  fileList() {

    let imgArr=this.data.imgArr;
    app.$post("/user/book/fileList", {
      // page: this.data.img_page,
      // pageSize: this.data.img_pageSize,
      page: 1,
      pageSize: 1000,
      bookId: this.data.queryData.bookId,
      // chapter: this.data.queryData.value
    }).then(res => {
      
      if (res.code == 200) {
        // let arr_list = imgArr.concat(res.data.list);
        let arr_list = res.data.list;

        let img_page = this.data.img_page;
        img_page = img_page + 1;
        // console.log(JSON.stringify(arr_list[0]));
        this.setData({
          // img_totalResult: res.data.totalResult,
          // img_page,
          imgArr: arr_list,
          showLoadMoreTxt: "over"
        });
        
      } 
    });
  },

  fileChange(e) {
    // console.log(type);
    let _this = this;
    dd.chooseImage({
      count: 3,
      success: (res) => {
        //console.log(res);
        try {
          let imgArr = [];
          for (let index = 0; index < res.filePaths.length; index++) {
            let url = res.filePaths[index];
            let arr = url.split("https://resource/");
            let name = arr[1];
            let json = {
              imgUrl: url,
              name,
              url,
              bookId: _this.data.queryData.bookId,
              bookName: _this.data.queryData.bookName,
              chapter: _this.data.queryData.value
            }
            imgArr.push(json);

            let api = "/user/book/addFile";
           // api="/file/upload"
            app.$postFile(api,json).then(res => {
              // console.log("--addFile返回数据:",res);
              //let response=JSON.parse(res);
              // if (response.code == 200) {
              // }else{
              // }
              // console.log("--index",index);
              // console.log("--imgArr.length-1:",(imgArr.length-1));
              if(index==imgArr.length-1){
                util.messageSuccess("上传成功!");
                _this.fileList();
              }
            });
          }

          // console.log(type);
          console.log("----imgArr::", JSON.stringify(imgArr));

          // this.setData({
          //   [`searchList.${type}`]: this.data.searchList[type].concat(imgArr)
          // })
        } catch (e) {
          console.log(e);
        }
      },
      fail: (err) => {
        // #ifdef MP
        dd.showModal({
          title: '授权失败',
          content: '钉钉小程序 需要从您的相册获取图片，请在设置界面打开相关权限',
          success: (res) => {
          }
        })
        // #endif
      }
    })
  },

  deleteFileFn(e){
    let id = e.currentTarget.dataset.id;
    let index = e.currentTarget.dataset.index;
    console.log("--删除下标:",index);
    dd.confirm({
      title: '温馨提示',
      content: '是否删除该图片?',
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      success: (result) => {
        if (result.confirm) {
          let data={
            fileId:id
          }
          let api = "/user/book/deleteFile";
          let imgArr=this.data.imgArr
          app.$post(api,data).then(res => {
            if (res.code == 200) {
              imgArr.splice(index, 1);
              util.messageSuccess("删除成功!");

              this.setData({
                imgArr
              })
            }
          }); 
        }
      },
    });
  },
  showImgList(){
    this.setData({
      showImg:true
    });
    this.fileList()
  },
  closeImgList(){
    this.setData({
      showImg:false
    });
  },
  onButtonTap(data, e) {
    console.log(data, e);
  },
  openDeleteImgFn(){
    let showDeleteImg=this.data.showDeleteImg;
    this.setData({
      showDeleteImg:!showDeleteImg
    })
  },
  closeDeleteImgFn(){
    this.setData({
      showDeleteImg:false
    })
  },
});